#include <QHeaderView>
#include <QContextMenuEvent>
#include <QMenu>

#include <QtDebug>

#include "SudokuDiagram.h"

SudokuDiagram::SudokuDiagram(QWidget* parent) :
        QTableView(parent),
        mDelegate(new SudokuGraphicsCellDelegate(this))
{
    verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // Keep aspect ratio row / col
    //TODO not working
    sizePolicy().setHeightForWidth(true);

    setItemDelegate(mDelegate);
}

void SudokuDiagram::contextMenuEvent(QContextMenuEvent* event)
{
    QModelIndex Index = indexAt(event->pos());
    QList<QVariant> candidateList = Index.data(SudokuDataModel::ContextMenuRole).toList();

    QMenu contextMenu(this);

    QListIterator<QVariant> iterator(candidateList);
    while (iterator.hasNext())
    {
        // +1 because candidates are indexed from 0
        int candidateNumber = iterator.next().toInt() + 1;
        QAction* setValueAction = new QAction(QString::number(candidateNumber), &contextMenu);
        setValueAction->setData(candidateNumber);
        contextMenu.addAction(setValueAction);
    }

    QAction* selectedAction = contextMenu.exec(event->globalPos());

    if(selectedAction)
    {
        bool ok = false;
        int selectedValue = selectedAction->data().toInt(&ok);
        qDebug() << "SudokuDiagram::contextMenuEvent selected=" << selectedValue;
        if(ok)
        {
            model()->setData(Index, selectedValue);
        }
    }

    closePersistentEditor(Index);
}

int SudokuDiagram::heightForWidth (int w) const
{
    qDebug() << "SudokuDiagram::heightForWidth " << w;
    return w;
}
